package com.liguang.rcs.admin.auth;

import com.liguang.rcs.admin.db.entity.DodmsUserEntity;
import com.liguang.rcs.admin.service.DodmsPermissionService;
import com.liguang.rcs.admin.service.DodmsRoleService;
import com.liguang.rcs.admin.service.DodmsUserService;
import com.liguang.rcs.admin.util.bcrypt.BCryptPasswordEncoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;

@Slf4j
public class UserAuthorizingRealm extends AuthorizingRealm {


    @Autowired
    private DodmsUserService userService;
    @Autowired
    private DodmsRoleService roleService;
    @Autowired
    private DodmsPermissionService permissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        if (principals == null) {
            throw new AuthenticationException("PrincipalCollection method argument cannot be null.");
        }

        DodmsUserEntity user = (DodmsUserEntity) getAvailablePrincipal(principals);
        Long[] roleIds = user.getRoleIds();
        Set<String> roles = roleService.queryByIds(roleIds);
        Set<String> permissions = permissionService.queryByRoleId(roleIds);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        String password=new String(upToken.getPassword());

        if (StringUtils.isEmpty(username)) {
            throw new AccountException("用户名不能为空");
        }
        if (StringUtils.isEmpty(password)) {
            throw new AccountException("密码不能为空");
        }
        List<DodmsUserEntity> adminList =null;
        try {
            adminList = userService.findUser(username);
        } catch (Exception ex) {
            log.error("Err, Exception:", ex);
            throw new RuntimeException(ex);
        }

        Assert.state(adminList.size() < 2, "同一个用户名存在两个账户");
        if (adminList.size() == 0) {
            throw new UnknownAccountException("找不到用户（"+username+"）的帐号信息");
        }
        DodmsUserEntity user = adminList.get(0);

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if (!encoder.matches(password, user.getPassword())) {
            throw new UnknownAccountException("找不到用户（"+username+"）的帐号信息");
        }

        return new SimpleAuthenticationInfo(user,password,getName());
    }


}
